//
//  TGMAlertView.m
//  TravelGuideMdd
//
//  Created by 陈曦 on 13-6-28.
//  Copyright (c) 2013年 mafengwo.com. All rights reserved.
//

#import "UIAlertView+TGMStyle.h"
#import <objc/runtime.h>
#import "Utils_Swizzing.h"
// 存储旧函数指针
static void (*oldSetSelected)(id self,SEL _cmd,BOOL selected);
static void (*oldSetHighLighted)(id self,SEL _cmd,BOOL selected);
static void (*oldAddSubview)(id self,SEL _cmd,UIView *view);
static void (*oldLayoutSubviews)(id self,SEL _cmd);

static const char UIAlertViewButtonShowViewKey;
static const char UIAlertViewButtonAlwaysHightLightKey;
static const char UIAlertViewHighlightButtonTitleKey;
static const char UIAlertViewButtonTitleLableKey;

static const char UIAlertViewButtonSelectViewKey;
static const char UIAlertViewButtonHighLightViewKey;

// 新选择
static void newSetSelected(UIButton *self, SEL _cmd,BOOL selected)
{
    if (newSetSelected != oldSetSelected)
    {
         objc_runOldMethod(self.class,oldSetSelected,self,_cmd,selected);
    }
    self.imageView.alpha = 0;
    
    UIView *selectedView = objc_getAssociatedObject(self, &UIAlertViewButtonSelectViewKey);
    if (!selectedView)
    {
        selectedView = [[UIView alloc] initWithFrame:self.bounds];
        selectedView.userInteractionEnabled = NO;
        objc_setAssociatedObject(self, &UIAlertViewButtonSelectViewKey, selectedView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [self addSubview:selectedView];
        selectedView.hidden = YES;
        selectedView.backgroundColor = C_RGB_A(0, 0.05);
    }
    selectedView.hidden = !selected;
}

// 添加视图
static void newAddSubview(UIButton *self,SEL _cmd,UIView *view)
{
    UILabel *lbl = objc_getAssociatedObject(self, &UIAlertViewButtonTitleLableKey);
    UIView *v = objc_getAssociatedObject(self, &UIAlertViewButtonShowViewKey);
    UIView *v2 = objc_getAssociatedObject(self, &UIAlertViewButtonHighLightViewKey);
    if (view == lbl || view == v || view == v2)
    {
        objc_runOldMethod(self.class,oldAddSubview,self,_cmd,view);
    }
}

// 高亮
static void newSetHighLighted(UIButton *self, SEL _cmd,BOOL highlighted)
{
    NSNumber *alwaysHighlight = objc_getAssociatedObject(self, &UIAlertViewButtonAlwaysHightLightKey);
    objc_runOldMethod(self.class,oldSetHighLighted,self,_cmd,highlighted);
    UIView *view = objc_getAssociatedObject(self, &UIAlertViewButtonShowViewKey);
    UILabel *lbl = objc_getAssociatedObject(self, &UIAlertViewButtonTitleLableKey);
    UIView *highLightView = objc_getAssociatedObject(self, &UIAlertViewButtonHighLightViewKey);
    
    if (alwaysHighlight.boolValue)
    {
        view.backgroundColor = C_RGB(0xf39c11);
        lbl.textColor = [UIColor whiteColor];
    }
    else
    {
        view.backgroundColor = C_RGB(0xf3f3f3);
        lbl.textColor = C_RGB(0x333333);
    }
    
    highLightView.hidden = !highlighted;
}

static void newLayoutSubviews(UIAlertView *self,SEL _cmd)
{
    objc_runOldMethod([UIAlertView class],oldLayoutSubviews,self,_cmd);
    NSMutableArray *buttons= [[NSMutableArray alloc] init];
    NSMutableArray *images = [[NSMutableArray alloc] init];
    NSMutableArray *labels = [[NSMutableArray alloc] init];
    [self.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([UIImageView class] == [obj class])
        {
            [images addObject:obj];
        }
        else if ([UILabel class] == [obj class])
        {
            [labels addObject:obj];
        }
        else if ([obj isKindOfClass:[UIButton class]])
        {
            [buttons addObject:obj];
        }
    }];
    
    if (images.count > 0)
    {
        UIImageView *imageView = images[0];
        CGRect frame = self.bounds;
        frame.size.height -= 5;
        imageView.frame = frame;
        
        imageView.image = nil;
        imageView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"all_view_bg"]];
    }
    
    if (images.count > 1)
    {
        UIImageView *imageView = images[1];
        imageView.alpha = 0;
    }
    
    if (labels.count > 0)
    {
        UILabel *lbl = labels[0];
        lbl.textColor = C_RGB(0x333333);
        lbl.shadowColor = [UIColor clearColor];
        lbl.shadowOffset = CGSizeMake(0,0);
    }

    if (labels.count > 1)
    {
        UILabel *lbl = labels[1];
        lbl.textColor = C_RGB(0x696969);
        lbl.shadowColor = [UIColor clearColor];
        lbl.shadowOffset = CGSizeMake(0,0);
    }
    
    if (buttons.count == 1)
    {
        [self setHighLightTitle:[buttons.lastObject title]];
    }
    
    [buttons enumerateObjectsUsingBlock:^(UIButton *btn, NSUInteger idx, BOOL *stop) {
        [btn.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        
        NSString *hightLightTitle = objc_getAssociatedObject(self, &UIAlertViewHighlightButtonTitleKey);
        if (hightLightTitle.length && [hightLightTitle isEqualToString:btn.currentTitle])
        {
            objc_setAssociatedObject(btn,&UIAlertViewButtonAlwaysHightLightKey,
                                     [NSNumber numberWithBool:YES],
                                     OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        }
        
        // 添加背景
        UIView *view = [[UIView alloc] initWithFrame:btn.bounds];
        objc_setAssociatedObject(btn,
                                 &UIAlertViewButtonShowViewKey,
                                 view,
                                 OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        
        view.userInteractionEnabled = NO;
        [btn addSubview:view];
        
        // 文字label
        UILabel *titleLable = [[UILabel alloc] initWithFrame:btn.bounds];
        
        titleLable.textColor = C_RGB(0x333333);;
        titleLable.textAlignment = NSTextAlignmentCenter;
        titleLable.font = [UIFont boldSystemFontOfSize:15];
        titleLable.text = btn.currentTitle;
        objc_setAssociatedObject(btn,
                                 &UIAlertViewButtonTitleLableKey,
                                 titleLable,
                                 OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [btn addSubview:titleLable];
        
        // 高亮
        UIView *highLightView = [[UIView alloc] initWithFrame:btn.bounds];
        highLightView.userInteractionEnabled = NO;
        objc_setAssociatedObject(btn, &UIAlertViewButtonHighLightViewKey, highLightView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [btn addSubview:highLightView];
        highLightView.hidden = YES;
        highLightView.backgroundColor = C_RGB_A(0, 0.05);
        
        if (!oldSetHighLighted)
        {
            oldSetHighLighted = objc_changeMethod(btn.class,
                                                  @selector(setHighlighted:),
                                                  newSetHighLighted);
        }
        if (!oldSetSelected)
        {
            oldSetSelected = objc_changeMethod(btn.class,
                                               @selector(setSelected:),
                                               newSetSelected);
        }
        
        if (!oldAddSubview)
        {
            oldAddSubview = objc_changeMethod(btn.class, @selector(addSubview:), newAddSubview);
        }
        
        btn.highlighted = btn.highlighted;
        btn.selected = btn.selected;
    }];
}

@implementation UIAlertView(TGMSTYLE)

+ (void)load
{
    oldLayoutSubviews = objc_changeMethod(self, @selector(layoutSubviews), newLayoutSubviews);
    oldSetSelected = nil;
    oldSetHighLighted = nil;
    oldAddSubview = nil;
}

- (void)setHighLightTitle:(NSString *)aTitle
{
    objc_setAssociatedObject(self,
                             &UIAlertViewHighlightButtonTitleKey,
                             aTitle,
                             OBJC_ASSOCIATION_COPY_NONATOMIC);
}

@end
